//
//  KZRainView.m
//  听说弱点强化训练
//
//  Created by 朱凯 on 2018/10/26.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "KZRainView.h"

@implementation KZRainView
{
    NSTimer *_timer;
}
- (instancetype)init {
    if (self = [super init]) {
    }
    return self;
}
- (void)startRain {
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.4 target:self selector:@selector(rain) userInfo:nil repeats:true];
}
- (void)stopRain {
    [_timer invalidate];
    _timer = nil;
}
- (void)rain {
    NSLog(@"count:%li", self.subviews.count);
    
    NSArray *raindrops = @[@"kz-雨滴1", @"kz-雨滴2", @"kz-雨滴3"];
    int r = arc4random_uniform(3);
    
    UIImageView *raindropView = [UIImageView new];
    raindropView.image = [UIImage imageNamed:raindrops[r]];
    [self addSubview:raindropView];
    [raindropView sizeToFit];
    raindropView.bottom = 0;
    raindropView.left = arc4random_uniform(self.width - raindropView.width);
    
    CABasicAnimation *ani = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
    ani.duration = (arc4random_uniform(30) + 20.0) / 20;
    ani.toValue = @(self.height);
    ani.removedOnCompletion = true;
    ani.timingFunction = [CAMediaTimingFunction functionWithControlPoints:1 :0 :1 :1];
    [raindropView.layer addAnimation:ani forKey:@"ani"];
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [raindropView removeFromSuperview];
    });
}

@end
